/**
 * creater:chuanpeng.zhu@dhc.com.cn
 * create time:2016-06-02 09:05:34
 * describe:数据持久化样例
 */
APP.controller('SaveExampleController', ['$scope', 'SaveExampleService', '$localstorage', 'CacheService', '$timeout',
  function ($scope, SaveExampleService, $localstorage, CacheService, $timeout) {

    /***变量声明***/
    var SAVE_EXAMPLE_KEY = 'SAVE_EXAMPLE_KEY';
    var SAVE_EXAMPLE_FLAG = 'SAVE_EXAMPLE_FLAG';
    $scope.data = {
      value: '',
      cacheOrStorage: 'cache'
    };
    $scope.todoList = undefined;
    /**
     * 初始化函数
     */
    $scope.init = function () {
      $scope.data = {
        value: '',
        cacheOrStorage: $localstorage.get(SAVE_EXAMPLE_FLAG) || 'cache'
      };

      $scope.todoList = getData();
      $scope.$broadcast('scroll.refreshComplete');
    };

    /**
     * button点击响应函数
     */
    $scope.addTodo = function () {
      $scope.todoList.push($scope.data.value);
      setData();
      $scope.data.value = '';
    };

    /**
     * 删除Todo，响应X按钮
     */
    $scope.deleteTodo = function (index) {
      $scope.todoList.splice(index, 1);
      setData();
    };

    /**
     * 监视data.cacheOrStorage变化，每次变化进行存储
     * 为了让页面记住是什么模式，所以需要将模式变量保存下来。
     */
    $scope.$watch('data.cacheOrStorage', function (newVal, oldVal, scope) {
      console.log('newVal:', newVal);
      $localstorage.set(SAVE_EXAMPLE_FLAG, newVal);
    });

    var setData = function () {
      if ($scope.data.cacheOrStorage == 'cache') {
        CacheService.set(SAVE_EXAMPLE_KEY, $scope.todoList);
      } else {
        $localstorage.setArray(SAVE_EXAMPLE_KEY, $scope.todoList)
      }
    };
    var getData = function () {
      if ($scope.data.cacheOrStorage == 'cache') {
        var temp = CacheService.get(SAVE_EXAMPLE_KEY);
        if (!!temp) {
          return temp;
        } else {
          return [];
        }
      } else {
        return $localstorage.getArray(SAVE_EXAMPLE_KEY);
      }
    };

    /*
     $scope.init();//如果页面缓存则用此方法初始化
     */
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.init();
    });
  }
]);

/**
 * creater:chuanpeng.zhu@dhc.com.cn
 * create time:2016-06-02 09:05:34
 * describe:数据持久化样例
 */
APP.service('SaveExampleService', ['$http', 'UrlService', function ($http, UrlService) {
  /**
   * 登录方法
   * @param username  登录用户名
   * @param password  登录密码
   */
  this.doLogin = function (username, password) {
    var param = {
      username: username,
      password: password
    };
    $http.post(UrlService.get('LOGIN'), param);
  }

}]);
